<?php
class ControllerSaleMailTemplate extends AdminController {

	public function index() {
		M('sale/mail_template', 'tpl_mod');
		$this->getList();
	}

	public function insert() {
		M('sale/mail_template', 'tpl_mod');
		if ($this->request->isPost()) {
			$this->tpl_mod->addMailTemplate($this->request->post);

			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('sale/mail_template'));
		}
		$this->getForm();
	}

	public function update() {
		M('sale/mail_template', 'tpl_mod');
		if ($this->request->isPost()) {
			$this->tpl_mod->editMailTemplate($this->request->get['mail_template_id'], $this->request->post);
				
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('sale/mail_template'));
		}
		$this->getForm();
	}

	public function delete() {
		M('sale/mail_template', 'tpl_mod');
		if ($this->request->post['selected']) {
			$this->tpl_mod->deleteMailTemplate($this->request->post['selected']);
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('sale/mail_template'));
		}
		$this->getList();
	}

	protected function getList() {
		$this->document->setTitle($this->_['heading_title']);
		
		$qf = new Query_filter();
		$total = $this->tpl_mod->getTotalMailTemplates();
		$this->data['templates'] = $this->tpl_mod->getMailTemplates($qf);
		$this->data['pagination'] = $this->pagination($total)->render();
	
		$this->display('sale/mail_template_list.tpl');
	}

	protected function getForm() {
		$this->document->addScript(ROOT . 'static/javascript/jquery/jquery.validate.js');
		$this->document->setTitle($this->_['heading_title']);
		$mail_template_id = G('mail_template_id');
		if ($mail_template_id) {
			$this->data['action'] = UA('sale/mail_template/update', "mail_template_id=$mail_template_id");
			if (!$this->request->isPost()) {
				$this->vo->data = $this->tpl_mod->getMailTemplate($mail_template_id);
			}
		}
		else {
			$this->data['action'] = UA('sale/mail_template/insert');
		}
		
		$this->display('sale/mail_template_form.tpl');
	}
}